package com.ball.common.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer, CorsConfigurationSource {
  // 添加中文注释
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    // 添加映射路径
    registry.addMapping("/api/**")
        // 允许任何域名访问
        .allowedOrigins("*")
        // 允许任何请求方法
        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
        // 允许任何请求头
        .allowedHeaders("*")
        // 允许跨域
        .allowCredentials(true)
//         设置最大有效时间
        .maxAge(3600);
  }

  @Override
  public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
    // 创建CorsConfiguration对象
    CorsConfiguration config = new CorsConfiguration();
    // 添加允许的域名
    config.addAllowedOrigin("*");
    // 添加允许的请求方法
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    // 添加允许的请求头
    config.addAllowedHeader("*");
    // 允许跨域
    config.setAllowCredentials(true);
    // 设置最大有效时间
    config.setMaxAge(3600L);
    // 返回CorsConfiguration对象
    return config;
  }
}